package swing.chapter03;

import swing.util.SwingConsle;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 消息框
 */
public class MessageBoxes extends JFrame {
    private JButton[] btns = {
            new JButton("Alert"),
            new JButton("Yes/No"),
            new JButton("Color"),
            new JButton("Input"),
            new JButton("3 Vals"),
    };
    private JTextField txt = new JTextField(20);

    private ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String id = ((JButton)e.getSource()).getText();
            switch (id){
                case "Alert": JOptionPane.showMessageDialog(null, "这里有个bug", "哈喽", JOptionPane.ERROR_MESSAGE); break;
                case "Yes/No": JOptionPane.showMessageDialog(null, "or no", "choose yes", JOptionPane.YES_NO_CANCEL_OPTION); break;
                case "Color": {
                    Object[] options = {"Red", "Yellow"};
                    int sel = JOptionPane.showOptionDialog(null, "选择一个颜色", "警告", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                    if(sel != JOptionPane.CLOSED_OPTION){
                        txt.setText("选择的颜色是：" + options[sel]);
                    }
                    break;
                }
                case "Input": {
                    String val = JOptionPane.showInputDialog("请输入内容：");
                    txt.setText(val);
                    break;
                }
                case "3 Vals": {
                    Object[] selections = {"One", "Two", "Three"};
                    Object val = JOptionPane.showInputDialog(null, "Choose one", "Input", JOptionPane.INFORMATION_MESSAGE, null, selections, selections[0]);
                    if(val != null){
                        txt.setText(val.toString());
                    }
                }
            }
        }
    };

    public MessageBoxes(){
        setLayout(new FlowLayout());
        for(int i=0;i<btns.length;i++){
            btns[i].addActionListener(al);
            add(btns[i]);
        }
        add(txt);
    }

    public static void main(String[] args) {
        SwingConsle.run(new MessageBoxes(), 400, 200);
    }
}
